#!/usr/bin/env python

import sys
import csv

# http://code.activestate.com/recipes/410687/
# http://docs.python.org/library/csv.html#csv-fmt-params

def gen_matrix(list):
    # need to find way to escape tru commas
    matrix = [row.rstrip().split(',') for row in list]
    return matrix

def transpose2(csv, out):
    csv_in = open(csv,'r')
    rows = csv_in.readlines()
    matrix = matrix = [row.rstrip().split(',') for row in rows]
    new_rows = flip(matrix)
    csv_out = open(out,'w')
    for row in new_rows:
     csv_out.write('%s\n' % (','.join(row)))
    csv_out.close()
    
# working method...
def transpose(matrix, defval=''):
    flipped = map(lambda *row: [elem or defval for elem in row], *matrix)
    #flipped = map(lambda *row: list(row), *matrix)
    return flipped

def process(csv_in, csv_out,sniff=False):
    csv_file = open(csv_in,'rb')
    # first make ';' for real commas
    # TODO NUMBERS dialect
    if sniff:
      dialect = csv.Sniffer().sniff(csv_file.read())
      #dialect.delimiter = ','
      csv_file.seek(0)
      reader = [row for row in csv.reader(csv_file, dialect)]
    else:
      reader = [row for row in csv.reader(csv_file, delimiter=',', doublequote=True, quotechar = "'",escapechar='"')]
    new_rows = transpose(reader)
    csv_file_out = open(csv_out,'w')
    for row in new_rows:
     csv_file_out.write('%s\n' % (','.join(row)))
    csv_file_out.close()
 
if __name__ == '__main__':

    if not len(sys.argv) > 2:
      sys.exit('\nProvide a csv file as input and output\n')
    process(str(sys.argv[1]),str(sys.argv[2]),sniff=True)